package com.sz.app.oss.api.common.contract;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.contract.entity.ContTemplate;
import com.sz.biz.common.contract.service.ServiceTypeEnum;
import com.sz.biz.common.contract.service.ContTemplateService;
import com.sz.biz.common.contract.dto.ContTemplateDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.utils.DateUtils;
import com.sz.biz.logistics.constants.ErrorCodes;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

/**
 * Function: 合同模板controller</br>
 * Author: yanhong.xiao.<br>
 * Date: 2017-07-19 14:53:00.
 */
@RestController
@RequestMapping("${api}/contracts/contract-templates")
@Api(description = " ", tags = "105-002，合同-合同模板管理")
public class ContTemplateController extends BaseController {
    @Autowired
    private ContTemplateService templateService;

    /**
     * @param
     * @param pageIndex
     * @param pageSize
     * @param sort
     * @param asc
     * @param startTime
     * @param endTime
     * @param serviceType
     * @param name
     * @param createUserName
     * @return
     */
    @ApiOperation(value = "合同模板列表以及查询接口", notes = "根据指定条件获取数据集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "int", paramType = "query", defaultValue
                    = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数,max<2000", dataType = "int", paramType = "query",
                    defaultValue = "10"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue =
                    "true"),
            @ApiImplicitParam(name = "serviceType", value = "业务类型", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "模板名称,模糊查询", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "createUserName", value = "创建者名称,模糊查询", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "string", paramType = "query")
    })
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResultDto find(@RequestParam(required = false, defaultValue = "1") int pageIndex,
                          @RequestParam(required = false, defaultValue = "10") int pageSize,
                          @RequestParam(required = false) String sort,
                          @RequestParam(required = false, defaultValue = "true") Boolean asc,
                          @RequestParam(required = false, defaultValue = "") String startTime,
                          @RequestParam(required = false, defaultValue = "") String endTime,
                          @RequestParam(required = false, defaultValue = "0") Integer serviceType,
                          @RequestParam(required = false) String name,
                          @RequestParam(required = false) String createUserName
    ) {
        QueryParams qp = new QueryParams(pageSize, pageIndex, null, sort, asc);
        if (null != ServiceTypeEnum.valueOfEnum(String.valueOf(serviceType))) {
            qp.put("serviceType", serviceType);
        }
        if (StringUtils.isNotBlank(name)) {
            name = com.sz.common.base.utils.StringUtils.replaceSqlPattern(name);
            qp.put("name", name.trim());
        }
        if (StringUtils.isNotBlank(createUserName)) {
            createUserName  = com.sz.common.base.utils.StringUtils.replaceSqlPattern(createUserName);
            qp.put("createUserName", createUserName.trim());
        }
        try {
            if (!ObjectUtils.isEmpty(startTime)) {
                qp.put("startTime", DateUtils.convertToDate(startTime, DateUtils.FORMAT_DETAIL));
            }
            if (!ObjectUtils.isEmpty(endTime)) {
                qp.put("endTime", DateUtils.convertToDate(endTime, DateUtils.FORMAT_DETAIL));
            }
        } catch (ParseException e) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_ILLEGAL, "startTime or endTime ");
        }
        return templateService.findSimpleDtoPages(qp);
    }


    /**
     * 新增合同模板
     */
    @ApiOperation(value = "新增合同模板", notes = "新增合同模板<br>权限："+Permissions.BIZ_MGT_BASE_CONT_TEMPLATE)
    @RequestMapping(value = "", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_CONT_TEMPLATE})
    public ResultDto save(@RequestBody @ApiParam(value = "要保存的数据", required = true) @Validated ContTemplateDto dto) {
        ContTemplate template = templateService.saveTemplate(dto);
        ResultDto result = getSaveSuccessDto(MessagesCodes.MODULE_CONT_TEMPLATE);
        result.setData(template.getId());
        return result;
    }


    /**
     * 修改合同模板
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    @ApiOperation(value = "修改合同模板", notes = "修改合同模板<br>权限:"+Permissions.BIZ_MGT_BASE_CONT_TEMPLATE)
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_CONT_TEMPLATE})
    public ResultDto update(@RequestBody ContTemplateDto dto, @PathVariable Integer id) {
        dto.setId(id);
        templateService.updateTemplate(dto);
        ResultDto result = getUpdateSuccessDto(MessagesCodes.MODULE_CONT_TEMPLATE);
        result.setData(dto.getId());
        return result;
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    @ApiOperation(value = "获取合同模板的详情", notes = "获取合同模板详情<br>权限："+Permissions.BIZ_MGT_BASE_CONT_TEMPLATE)
    public ResultDto getById(@PathVariable Integer id) {
        ContTemplateDto dto = templateService.getDtoById(id);
        ResultDto resultDto = new ResultDto();
        resultDto.setData(dto);
        return resultDto;
    }


    @ApiOperation(value = "根据id批量删除", notes = "根据id批量删除</br>权限"+Permissions.BIZ_MGT_BASE_CONT_TEMPLATE, httpMethod = "POST")
    @RequestMapping(value = "/deletions", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_CONT_TEMPLATE})
    public ResultDto batchDelete(@RequestBody @ApiParam(value = "要删除的id集合", required = true) List<Integer> ids) {
        templateService.batchDeleteByIds(ids);
        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_CONT_TEMPLATE);
        return dto;
    }


    @ApiOperation(value = "下拉框中查询合同模板的id，name专用接口", notes = "下拉框中查询合同模板的id，name专用接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "int", paramType = "query", defaultValue
                    = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数,max<2000", dataType = "int", paramType = "query",
                    defaultValue = "10"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue =
                    "true"),
            @ApiImplicitParam(name = "serviceType", value = "业务类型", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "模板名称", dataType = "string", paramType = "query"),
    })
    @RequestMapping(value = "/simpleList", method = RequestMethod.GET)
    public ResultDto getSimpleList(@RequestParam(required = false, defaultValue = "1") int pageIndex,
                                   @RequestParam(required = false, defaultValue = "10") int pageSize,
                                   @RequestParam(required = false) String sort,
                                   @RequestParam(required = false, defaultValue = "true") Boolean asc,
                                   @RequestParam(required = false, defaultValue = "0") Integer serviceType,
                                   @RequestParam(required = false) String name) {
        QueryParams qp = new QueryParams(pageSize, pageIndex, null, sort, asc);
        if (StringUtils.isNotBlank(name)) {
            name  = com.sz.common.base.utils.StringUtils.replaceSqlPattern(name);
            qp.put("name", name);
        }
        if (null != ServiceTypeEnum.valueOfEnum(String.valueOf(serviceType))) {
            qp.put("serviceType", serviceType);
        }
        return templateService.findMinDtoPages(qp);
    }


    /**
     * 异步校验合同模板的名称是否重复
     */

    @ApiOperation(value = "校验合同模板名称的唯一性", notes = "校验合同模板名称的唯一性")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "id", value = "模板id,修改中校验时需要进行传值", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "模板名称", dataType = "string", paramType = "query")
    })
    @RequestMapping(value = "/names/check", method = {RequestMethod.GET})
    public ResultDto checkName(@RequestParam(required = false) Integer id, String name) {
        ResultDto resultDto = new ResultDto();
        if (templateService.checkUniqueName(id, name)) {
            //已经存在
            resultDto.setData(Boolean.TRUE);
        } else {
            //不存在
            resultDto.setData(Boolean.FALSE);
        }
        return resultDto;
    }


}
